<?php

/**
 * +----------------------------------------------------------------------
 * | TickyPHP [ This is a freeware ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2015 All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: 罗敏贵 <e-mail:minguiluo@163.com> <QQ:271391233>
 * +----------------------------------------------------------------------
 * | SVN: $Id: Member.php 87573 2018-09-04 09:49:32 luomingui $
 * +----------------------------------------------------------------------
 * | 文件功能：对应的表名:tky_member
 * +----------------------------------------------------------------------
 */

namespace application\member\controller;

use application\admin\controller\base as auth;
use ticky\request;
use ticky\response;
use application\member\models\point;

class member extends auth {

    public $member_status = array('0' => '待审核', '1' => '通过审核', '2' => '账号锁定');  //订单状态

    public function index() {
        $search = $this->search_frm();
        $ret = db('member')->where($search['sql'])->newpage();
        foreach ($ret['items'] as $row) {
            if ($row['lastlogintime'] == '0') {
                $row['lastlogintime'] = "未登陆";
            } else {
                $row['lastlogintime'] = date("Y-m-d H:i:s", $row['lastlogintime']);
            }
            $data[] = $row;
        }
        $this->assign('page', $ret['page']);
        $this->assign('items', $data);
        $this->assign('search', $search['arr']);
        $this->assign('default_password', get_config('default_password'));
        $this->display('member/index');
    }

    // 添加记录
    public function add() {
        if (request::isPost()) {
            $data = $this->post_frm();
            $data['password'] = authcode(get_config('default_password'), 'ENCODE');
            //根据用户组获取最小经验
            $data['experience'] = $this->get_experience($data['groupid']);
            $userid = db('member')->insert($data);
            if ($userid) {
                db('member_profile')->insert(array('uid' => $userid, 'realname' => $_POST['realname'])); //插入附表
            }
            showmsg('添加成功', '/admin/member');
        } else {
            $this->assign('postUrl', '/member/member/add');
            $this->assign('action', '添加');
            $this->display('member/member_add');
        }
    }

    // 更新记录
    public function update() {
        load_extend('form.class.php');
        $uid = request::get('uid', 0);
        $member = db('member')->where(array('uid' => $uid))->find();
        if (request::isPost()) {
            $member_profile = db('member_profile')->where(array('uid' => $uid))->find();
            if ($member_profile) {
                db('member_profile')->update($_POST, array('uid' => $uid));
                $msg = "修改";
            } else {
                $msg = "添加";
                $_POST['uid'] = $uid;
                db('member_profile')->insert($_POST, false, false, false);
            }
            showmsg($msg . '用户详细信息成功', '/member/member');
        } else {
            $member_profile = db('member_profile')->where(array('uid' => $uid))->find();
            if ($member_profile) {
                $item = array_merge($member, $member_profile);
            } else {
                $item = $member;
            }

            $nowy = date('Y');
            $birthyeayhtml = '';
            for ($i = 0; $i < 100; $i++) {
                $they = $nowy - $i;
                if (empty($_GET['all']))
                    $selectstr = $they == $item['birthyear'] ? ' selected=\"selected\"' : '';
                $birthyeayhtml .= "<option value=\"$they\"$selectstr>$they</option>";
            }
            $birthmonthhtml = '';
            for ($i = 1; $i < 13; $i++) {
                if (empty($_GET['all']))
                    $selectstr = $i == $item['birthmonth'] ? ' selected=\"selected\"' : '';
                $birthmonthhtml .= "<option value=\"$i\"$selectstr>$i</option>";
            }
            $birthdayhtml = '';
            for ($i = 1; $i < 29; $i++) {
                if (empty($_GET['all']))
                    $selectstr = $i == $item['birthday'] ? ' selected=\"selected\"' : '';
                $birthdayhtml .= "<option value=\"$i\"$selectstr>$i</option>";
            }
            $this->assign('birthyeayhtml', $birthyeayhtml);
            $this->assign('birthmonthhtml', $birthmonthhtml);
            $this->assign('birthdayhtml', $birthdayhtml);

            $this->assign('postUrl', '/member/member/update');
            $this->assign('action', '更新');
            $this->assign('item', $item);
            $this->display('member/manage_edit');
        }
    }

    // 删除记录
    public function delete() {
        $id = request::get('id', 0);
        $result = db('member')->delete(['uid' => $id]);
        showmsg('删除成功', '/member/member');
    }

    // 批量删除
    public function batchremove() {
        $optype = request::post('optype', 'del');
        $ids = request::post('ids', []);
        $msg = "";
        $where = ' uid in(' . implode(",", $ids) . ') ';
        if ($optype == "del") {
            for ($i = 0; $i < count($ids); $i++) {
                $id = $ids[$i];
                db('member')->delete(array('uid' => $id));
                db('member_profile')->delete(array('uid' => $id));
            }
            $msg = "批量删除成功";
        } else if ($optype == 'check') {
            $msg = "批量设置待审核用户成功";
            db('member')->update(array('status' => '1'), $where);
        } else if ($optype == 'adopt') {
            $msg = "批量通过审核成功";
            db('member')->update(array('status' => '1'), $where);
        } else if ($optype == 'lock') {
            $msg = "批量锁定用户成功";
            db('member')->update(array('status' => '2'), $where);
        } else if ($optype == 'reset') {
            $msg = "批量重置用户密码为" . get_config('default_password') . "成功";
            db('member')->update(array('password' => authcode(get_config('default_password'), 'ENCODE')), $where);
        }
        header("location:/member/member/index");
    }

    //查询条件
    private function search_frm() {
        $where = '1=1 and adminid=0 ';
        $search = request::get('search', []);
        $search['groupid'] = request::get('groupid', 0);
        $type = request::get('type', '');
        $keyword = request::get('keyword', '');
        $search['type'] = $type;
        if ($keyword != '') {
            $search['keyword'] = $keyword;
            switch ($type) {
                case "username":
                    $where .= "and username LIKE '%" . $keyword . "%' ";
                    break;
                case "uid":
                    $where .= "and uid = '" . $keyword . "' ";
                    break;
                case "email":
                    $where .= "and email LIKE '%" . $keyword . "%' ";
                    break;
                case "loginnum":
                    $where .= "and loginnum = " . $keyword . " ";
                    break;
            }
        }
        if ($groupid = trim($search['groupid'])) {
            $where .= " and groupid = " . $groupid . " ";
        }
        if ($status = trim($search['status'])) {
            $where .= " and status = " . $status . " ";
        }
        //enddate
        if (isset($_GET['startdate']) && isset($_GET['enddate']) && $_GET['startdate']) {
            $where .= " AND `regdate` >= '" . strtotime($_GET['startdate']) . "' AND `regdate` <= '" . strtotime($_GET['enddate']) . "' ";
            $search['startdate'] = $_GET['startdate'];
            $search['enddate'] = $_GET['enddate'];
        } else {
            $search['enddate'] = date('Y-m-d');
        }
        return [
            'arr' => $search,
            'sql' => $where
        ];
    }

    //表单数据
    private function post_frm() {
        $arr = array();
        $arr['username'] = request::post('username', '');
        $arr['password'] = request::post('password', '');
        $arr['email'] = request::post('email', '');
        $arr['avatarstatus'] = request::post('avatarstatus', '0');
        $arr['amount'] = request::post('amount', '0');
        $arr['experience'] = request::post('experience', '0');
        $arr['regip'] = request::getClientIp();
        $arr['regdate'] = time();
        $arr['lastloginip'] = '';
        $arr['lastlogintime'] = '';
        $arr['loginnum'] = request::post('loginnum', '0');
        $arr['adminid'] = request::post('adminid', '0');
        $arr['groupid'] = request::post('groupid', '1');
        $arr['timeoffset'] = request::post('timeoffset', '');
        $arr['status'] = request::post('status', '0');
        $arr['dateline'] = time();
        return $arr;
    }

    /**
     * 根据用户组获取最小经验
     */
    private function get_experience($groupid) {
        if ($groupid == 1)
            return 0;
        $member_group = get_groupinfo();
        if ($member_group[$groupid - 1]) {
            return $member_group[$groupid - 1]['experience'] + 1;
        }
        return 0;
    }

    /**
     * 重置密码
     */
    public function reset_password() {
        $user_id = request::get('user_id', 0);
        $user = db('member')->where(array('uid' => $user_id))->find();
        if (!$user) {
            showmsg('抱歉，该会员不存在!');
        }
        $result = db('member')->where(['uid' => $user_id])->update(['password' => authcode(get_config('default_password'), 'ENCODE')]);
        showmsg('密码重置成功!');
    }

    /**
     * 修改密码
     */
    public function change_password() {
        if (request::isPost()) {
            $name = request::post('username', '');
            $password = request::post('password', '');
            $default_password = authcode($password, 'ENCODE');
            $user = db('member')->where(['username' => $name])->find();
            if ($user) {
                $result = db('member')->where(['username' => $name])->update(['password' => $default_password]);
                if ($result !== false) {
                    $msg = "更新成功!";
                } else {
                    $msg = "更新失败!";
                }
                showmsg($msg);
            } else {
                showmsg('抱歉，该会员不存在!');
            }
        } else {
            $this->display('member/change_password');
        }
    }

    /**
     * 待审核用户列表
     */
    public function check() {
        $ret = db('member')->where(array('status' => 0))->newpage();
        foreach ($ret['items'] as $row) {
            if ($row['lastlogintime'] == '0') {
                $row['lastlogintime'] = "未登陆";
            } else {
                $row['lastlogintime'] = date("Y-m-d H:i:s", $row['lastlogintime']);
            }
            $data[] = $row;
        }
        $this->assign('page', $ret['page']);
        $this->assign('items', $data);
        $this->display('member/member_check');
    }

    /**
     * 在线充值
     */
    public function recharge() {
        if (request::isPost()) {
            $username = isset($_POST['username']) && is_username($_POST['username']) ? trim($_POST['username']) : showmsg('用户名格式错误！');
            $userinfo = db('member')->field('uid,email')->where(array('username' => $username))->find();
            if ($userinfo) {
                if ($_POST['unit']) {
                    point::instance()->point_add($_POST['type'], floatval($_POST['money']), 4, $userinfo['userid'], $username, 0, $_POST['remarks'], $_SESSION['adminname'], false);
                } else {
                    point::instance()->point_spend($_POST['type'], floatval($_POST['money']), 4, $userinfo['userid'], $username, $_POST['remarks']);
                }
                //发送e-mail通知会员
                if (isset($_POST['sendemail'])) {
                    $type = $_POST['type'] == '1' ? '积分' : '元';
                    $content = '您的账户于' . date('Y-m-d H:i:s', SYS_TIME) . '成功充值' . floatval($_POST['money']) . $type . '，详情请登录会员中心查看。';
                    sendmail($userinfo['email'], '充值到账通知', $content);
                }
                $op = $_POST['unit'] == '1' ? 'pay' : 'pay_spend';
                showmsg('操作成功！', $op, 2);
            } else {
                showmsg('操作失败！');
            }
        } else {
            $this->display('member/recharge');
        }
    }

}
